package com.hh.start.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hh.start.common.BaseResponse;
import com.hh.start.common.ErrorCode;
import com.hh.start.common.ResultUtils;
import com.hh.start.exception.BusinessException;
import com.hh.start.model.domain.User;
import com.hh.start.model.domain.request.UserLoginRequset;
import com.hh.start.model.domain.request.UserRegisterRequest;
import com.hh.start.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;

import static com.hh.start.contant.UserContant.ADMIN_Role;
import static com.hh.start.contant.UserContant.USER_LOGIN_STATUS;
/**
 *  用户接口
 */
@RestController
@RequestMapping("/user")
public class userController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if(userRegisterRequest == null){
//            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if(StringUtils.isAllBlank(userAccount,userPassword,checkPassword)){
            return null;
        }
        long result = userService.userRegister(userAccount,userPassword,checkPassword,planetCode);

        return new BaseResponse<>(0,result,"ok");
//        return userService.userRegister(userAccount, userPassword, checkPassword,planetCode);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequset userLoginRequest, HttpServletRequest request) {
        if(userLoginRequest == null){
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAllBlank(userAccount,userPassword)){
            return null;
        }
        User user = userService.userLogin(userAccount, userPassword,request);
        // 正常返回
        // return userService.userLogin(userAccount, userPassword,request);
        // 通用类 返回
        //return new BaseResponse<>(0,user,"ok");
        // 工具类返回
        return ResultUtils.success(user);

    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User currentUser = (User) userObj;
        if(currentUser == null){
            return null;
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safeUser = userService.getSafeUser(user);
        return ResultUtils.success(safeUser);
        //  return userService.getSafeUser(user);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username,HttpServletRequest request) {
        if(!isAdmin(request)){
//            return new ArrayList<>();
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> {
           user.setUserPassword(null);
           return userService.getSafeUser(user);
       }).collect(Collectors.toList());

        return ResultUtils.success(list);

//       return userList.stream().map(user -> {
//           user.setUserPassword(null);
//           return userService.getSafeUser(user);
//       }).collect(Collectors.toList());
    }

    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id,HttpServletRequest request) {
        if(!isAdmin(request)){
            return null;
        }
        if (id <= 0){
            return null;
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout( HttpServletRequest request) {
        if(request == null){
            return null;
        }
        int i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    /**
     * 是否为管理员
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATUS);
        User user = (User) userObj;
        return user !=null && user.getUserRole() == ADMIN_Role;
        // 简写
        // if(user == null || user.getRole() != ADMIN_Role){
        //      return false;
        //  }
        //  return true;
    }

}
